﻿using BLL.Manager;
using Helper;
using HZY.Framework.DependencyInjection;
using Model.EntityInfo;
using Sunny.UI;
using WinFormsSprayProcessSCADASystem.Components;
using WinFormsSprayProcessSCADASystem.Extension;

namespace WinFormsSprayProcessSCADASystem.Pages
{
    public partial class PageRoleManage : UIPage, IScopedSelfDependency 
    {
        private readonly RoleManager _roleManager;
        private readonly RouteManager _routeManager;

        private List<RouteInfoModel> _routeList = new List<RouteInfoModel>();
        public PageRoleManage(RoleManager roleManager, RouteManager routeManager)
        {
            _roleManager = roleManager;
            _routeManager = routeManager;
            InitializeComponent();
            InitPage();

        }

        private void PageRoleManage_Shown(object sender, EventArgs e)
        {
            LoadData();
        }


        private void uiDataGridView1_CellContentClick(object? sender, UIDataGridViewActionCell.ButtonClickEventArgs e)
        {
            if (e.ButtonIndex == 0)
            {
                //编辑
                if (e.ButtonIndex == 0)
                {
                    RoleInfoModel row = ((List<RoleInfoModel>)uiDataGridView1.DataSource)[e.RowIndex];
                    DialogRoleEdit dialogRoleEdit = new DialogRoleEdit();
                    dialogRoleEdit.Routes = _routeList;
                    dialogRoleEdit.EditRoleData = new EditRoleData()
                    {
                        Id = row.Id,
                        Name = row.Name,
                        routeIds = row.Routes.Select(r => r.Id).ToList(),
                    };
                    dialogRoleEdit.Render();
                    dialogRoleEdit.ShowDialog();
                    if (dialogRoleEdit.IsOK)
                    {

                    }

                    dialogRoleEdit.Dispose();
                }
                else
                {

                }
            }
            else
            {

            }
        }
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void uiButton1_Click(object sender, EventArgs e)
        {
            DialogRoleEdit dialogRoleEdit = new DialogRoleEdit();
            dialogRoleEdit.Routes = _routeList;
            dialogRoleEdit.Render();
            dialogRoleEdit.ShowDialog();
            if (dialogRoleEdit.IsOK)
            {
                //this.ShowSuccessDialog(frm.Person.ToString());
                var res = await _roleManager.AddRoleAsync(new BLL.DTO.RoleDto.AddRoleDto()
                {
                    RoleName = dialogRoleEdit.EditRoleData.Name,
                    RouteIds = dialogRoleEdit.EditRoleData.routeIds
                });
                if (res.Code == SystemEnums.ResCode.Success)
                {
                    this.ShowOk("新增成功");
                    this.LogMes($"{Globals.CurrentUser.UserName}新增了角色{dialogRoleEdit.EditRoleData.Name}");
                    GetRoleListReqAsync().ConfigureAwait(false);
                }
                else
                {
                    this.LogError(res.Msg);
                    this.ShowError(res.Msg);
                }
            }

            dialogRoleEdit.Dispose();
        }

        private void LoadData()
        {
            try
            {
                GetRoleListReqAsync().ConfigureAwait(false);
                GetRouteListReqAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                // 记录错误日志
                MessageBox.Show($"加载数据失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        private async Task GetRoleListReqAsync()
        {
            BaseResult<List<RoleInfoModel>> res = await _roleManager.GetAllRole();

            // 使用 Control.Invoke 在UI线程上更新数据
            if (res.Code == SystemEnums.ResCode.Success && res.Data != null)
            {

                try
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        try
                        {
                            // 复制数据以减少UI线程操作时间
                            var dataCopy = new List<RoleInfoModel>(res.Data);

                            uiDataGridView1.DataSource = dataCopy;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Exception inside Invoke: {ex.Message}");
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Exception during Invoke: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine($"Data is null or code is not success. Code: {res.Code}, Data: {res.Data}");
            }
        }

        private async Task GetRouteListReqAsync()
        {
            var res = await _routeManager.GetAllRoute();

            if (res.Code == SystemEnums.ResCode.Success && res.Data != null)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    // 复制数据以减少UI线程操作时间
                    _routeList = new List<RouteInfoModel>(res.Data);

                });
            }
        }
        private void InitPage()
        {
            UIDataGridViewActionColumn actionColumn = uiDataGridView1.AddActionColumn("操作", 180, uiDataGridView1_CellContentClick, new UIDataGridViewActionCell.ActionBtn()
            {
                Text = "编辑",
                TypeKey = ETypeKey.primary
            }, new UIDataGridViewActionCell.ActionBtn()
            {
                Text = "删除",
                TypeKey = ETypeKey.warning
            });
        }
    }
}
